<template>
    <div class="select-map">
        <div class="box-wrap">
            <el-autocomplete
                v-model="address"
                v-if="!show"
                clearable
                :disabled="disabled"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearchAsync"
                placeholder="输入地址快速检索"
                @select="handleSelect">
                <template slot="append">
                    <el-button @click="openMap" :disabled="disabled"><i class="el-icon-location-information"></i>搜索</el-button>
                </template>
                <template slot-scope="{ item }">
                    <div class="name">{{ item.title }}</div>
                    <span class="addr" style="font-size:12px;color:#999;">{{ item.address }}</span>
                </template>
            </el-autocomplete>
        </div>
        <p v-if="address">
            {{ province }} &nbsp; {{ city }} &nbsp; {{ district }} &nbsp; {{ street }}{{ streetNumber }} 
        </p>
        <div class="pop-overlay" v-show="show">
            <div class="map-box">
                <div class="map-title">
                    {{ title }}
                    <div class="btn-wrap">
                        <i class="el-icon-circle-close" @click="closeMap"></i>
                    </div>
                </div>
                <div class="map-wrap">
                    <baidu-map 
                        ref="map"
                        class="bm-view" 
                        :center="center" 
                        :zoom="zoom" 
                        @ready="readyFun"
                        @click="mapClick">
                        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-map-type>
                        <bm-control :offset="{top: 10, left: 10}">
                            <el-autocomplete
                                v-model="address"
                                v-if="show"
                                clearable
                                :disabled="disabled"
                                :trigger-on-focus="false"
                                :fetch-suggestions="querySearchAsync"
                                placeholder="输入地址快速检索"
                                @select="handleSelect"
                                style="width:240px;margin:10px;">
                                <template slot-scope="{ item }">
                                    <div class="name">{{ item.title }}</div>
                                    <span class="addr" style="font-size:12px;color:#999;">{{ item.address }}</span>
                                </template>
                            </el-autocomplete>
                        </bm-control>
                    </baidu-map>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'selectMap', // 选择地图组件
        props: {
            value: { // v-model绑定值 全部路径的地址
                type: String,
                default: ''
            },
            lng: { // 经度
                type: [String, Number],
                default: ''
            },
            lat: { // 纬度
                type: [String, Number],
                default: ''
            },
            province: { // 省
                type: String,
                default: ''
            },
            city: { // 市
                type: String,
                default: ''
            },
            district: { // 区
                type: String,
                default: ''
            },
            street: { // 街道
                type: String,
                default: ''
            },
            streetNumber: { // 门牌号
                type: String,
                default: ''
            },
            disabled: {
                type: Boolean,
                default: false
            }
        },
        components: {},
        data() {
            return {
                title: '地点搜索',
                show: false,
                BMap: null,
                map: null,
                center: {lng: '', lat: ''},
                zoom: 15
            }
        },
        watch: {
            address(val) {
                if(!val) {
                    this.m_lng = '';
                    this.m_lat = '';
                    this.$emit('update:province', '');
                    this.$emit('update:city', '');
                    this.$emit('update:district', '');
                    this.$emit('update:street', '');
                }
            }
        },
        computed: {
            address: {
                get: function() {
                    return this.value
                },
                set: function(val) {
                    this.$emit('input', val);
                }
            },
            m_lng: {
                get: function() {
                    return this.lng;
                },
                set: function(val) {
                    this.$emit('update:lng', val);
                }
            },
            m_lat: {
                get: function() {
                    return this.lat;
                },
                set: function(val) {
                    this.$emit('update:lat', val);
                }
            }
        },
        methods: {
            openMap() {
                this.show = true;
                this.zoom = 15;
            },
            closeMap() {
                this.show = false;
            },
            readyFun({ BMap, map }) {
                this.BMap = BMap;
                this.map = map;
                let _this = this; // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(r){
					_this.center = {lng: r.longitude, lat: r.latitude}; // 设置center属性值
				},{enableHighAccuracy: true});
            },
            mapClick(e) {
                let _this = this;
                if(this.BMap) {
                    let geocoder= new this.BMap.Geocoder(); 
                    geocoder.getLocation(e.point, function(res) {
                        console.log(res)
                        _this.m_lng = res.point.lng;
                        _this.m_lat = res.point.lat;
                        let addressComponents = res.addressComponents;
                        _this.address = [addressComponents.district, addressComponents.street, addressComponents.streetNumber].join('');
                        _this.$emit('update:province', addressComponents.province);
                        _this.$emit('update:city', addressComponents.city);
                        _this.$emit('update:district', addressComponents.district);
                        _this.$emit('update:street', addressComponents.street);
                        _this.$emit('update:streetNumber', addressComponents.streetNumber);
                    })
                }
            },
            querySearchAsync(queryString, callback) {
                if(this.BMap) {
                    var local = new this.BMap.LocalSearch(this.map, {
                        renderOptions:{
                            map: this.map
                        },
                        onSearchComplete: function(results) {
                            // if(res && Array.isArray(res.Ar)) {
                            //     console.log(res)
                            //     let result = res.Ar;
                            //     result = result.map(item => {
                            //         return {
                            //             ...item,
                            //             label: item.title,
                            //             value: item.address
                            //         }
                            //     })
                            //     callback(result);
                            // }else {
                            //     callback([]);
                            // }
                            let resultArr = [];
                            for (var i = 0; i < results.getCurrentNumPois(); i++) {
                                resultArr.push(results.getPoi(i));
                            }
                            callback(resultArr);
                        }
                    });
                    local.search(queryString);
                }
            },
            handleSelect(item) {
                this.center = item.point;

                console.log(item)
                this.address = item.title;

                var _this = this;
                if(this.BMap) {
                    let geocoder= new this.BMap.Geocoder(); 
                    geocoder.getLocation(item.point, function(res) {
                        console.log(res)
                        _this.m_lng = res.point.lng;
                        _this.m_lat = res.point.lat;
                        let addressComponents = res.addressComponents;
                        _this.$emit('update:province', addressComponents.province);
                        _this.$emit('update:city', addressComponents.city);
                        _this.$emit('update:district', addressComponents.district);
                        _this.$emit('update:street', addressComponents.street);
                        _this.$emit('update:streetNumber', addressComponents.streetNumber);
                    })
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
.select-map {
    .bm-view {
        width: 100%;
        height: 100%;
    }
    .pop-overlay {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 2000;
        overflow: hidden;
        background-color: rgba(0, 0, 0, .3);
        .map-box {
            width: 75%;
            height: 85%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            flex-direction: column;
            background: #fff;
            .map-title {
                padding: 10px 10px 0;
                line-height: 30px;
                font-size: 16px;
                font-weight: 700;
                .btn-wrap {
                    float: right;
                    font-size: 24px;
                    cursor: pointer;
                }
            }
            .map-wrap {
                flex: 1;
                padding: 10px;
                overflow: hidden;
            }
        }
    }
}
</style>